<template>
  <router-view></router-view>
</template>

<script setup lang="ts">
import { onMounted, h } from 'vue'
import { useUsersStore } from './stores'
import { ElNotification, ElButton } from 'element-plus'
import Api from './api'
import { Bell, Notification } from '@element-plus/icons-vue'

const duration = 1000 * 60 * 10 // 检查间隔时间（毫秒）

// 检查用户是否登录
const isLoggedIn = () => !!sessionStorage.getItem('CURRENT_USER')

// 通用通知函数
const showNotification = (title: string, message: string, icon: any, onConfirm: () => void, onClose: () => void) => {
  const notification = ElNotification({
    title,
    duration: 0,
    icon,
    showClose: false,
    dangerouslyUseHTMLString: true,
    position: 'bottom-right',
    message: () =>
      h('p', [
        h('span', null, message),
        h(
          ElButton,
          {
            type: 'primary',
            size: 'small',
            plain: true,
            onClick: () => {
              onConfirm()
              notification.close()
            },
          },
          { default: () => '知道了' }
        ),
      ]),
    onClose,
  })
}

// 检查未审批的加班申请
const checkOverTime = async () => {
  if (!isLoggedIn()) {
    sessionStorage.setItem('OVERTIME_ISCHECKED', '0')
    setTimeout(checkOverTime, duration)
    return
  }

  if (useUsersStore().hasNotice) {
    const { rows } = await Api.Overtime.searchByUser({ pageSize: 9999, approvalUserName: useUsersStore().user.username })
    const overitemIsChecked = (sessionStorage.getItem('OVERTIME_ISCHECKED') || 0) as number
    if (rows && rows.length > 0 && overitemIsChecked == 0) {
      showNotification(
        '通知',
        '有未审批的加班申请，请及时处理。',
        Bell,
        () => {
          // sessionStorage.setItem('OVERTIME_ISCHECKED', '1')
        },
        () => setTimeout(checkOverTime, duration)
      )
    } else {
      setTimeout(checkOverTime, duration)
    }
  }
}

// 检查未审批的请假申请
const checkLeave = async () => {
  if (!isLoggedIn()) {
    sessionStorage.setItem('LEAVE_ISCHECKED', '0')
    setTimeout(checkLeave, duration)
    return
  }
  if (useUsersStore().hasNotice) {
    const rows = await Api.Leave.getListByProcessUser({ pageSize: 9999, approvalUserName: useUsersStore().user.username })
    const leaveIsChecked = (sessionStorage.getItem('LEAVE_ISCHECKED') || 0) as number
    if (rows && rows.length > 0 && leaveIsChecked == 0) {
      showNotification(
        '通知',
        '有未审批的请假申请，请及时处理。',
        Notification,
        () => {
          // sessionStorage.setItem('LEAVE_ISCHECKED', '1')
        },
        () => setTimeout(checkLeave, duration)
      )
    } else {
      setTimeout(checkLeave, duration)
    }
  }
}

// 初始化检查
onMounted(() => {
  checkOverTime()
  checkLeave()
})
</script>

<style scoped></style>
